package com.xyf.sys.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xyf.sys.config.CustomException;
import com.xyf.sys.domain.Role;
import com.xyf.sys.domain.UserAddress;
import com.xyf.sys.mapper.UserAddressMapper;
import com.xyf.sys.service.IUserAddressService;
import com.xyf.sys.service.IUserRoleService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @Author R-H
 * @Date 2024/2/241534
 * @Description
 */
@Service
public class UserAddressServiceImpl implements IUserAddressService {

    @Autowired
    private UserAddressMapper userAddressMapper;
    @Autowired
    private IUserRoleService userRoleService;

    @Override
    public PageInfo getPage(Integer pageNum, Integer pageSize, String userId, Integer type, String keyword, Long deptId, boolean client) {
        if (StringUtils.isNotBlank(keyword) && keyword.contains("#")){
            keyword = keyword.split("#")[0];
        }
        boolean regimentRole = false;
        if (!client){
            List<Role> roles = userRoleService.getRoleList(userId, deptId);
            regimentRole = !CollectionUtils.isEmpty(roles) && roles.stream().filter(role-> "REGIMENT".equalsIgnoreCase(role.getRoleKey()) || "AGENT".equalsIgnoreCase(role.getRoleKey())).findAny().isPresent();
        }
        PageHelper.startPage(pageNum, pageSize);
        List<UserAddress> list = userAddressMapper.selectUserAddressList(userId, type, regimentRole, keyword, deptId,"0");
        return new PageInfo(list);
    }

    @Override
    public List<UserAddress> getList(String userId, Integer type, String keyword) {
        List<Role> roles = userRoleService.getRoleList(userId);
        boolean regimentRole = !CollectionUtils.isEmpty(roles) && roles.stream().filter(role-> "REGIMENT".equalsIgnoreCase(role.getRoleKey())).findAny().isPresent();
        return userAddressMapper.selectUserAddressList(userId, type, regimentRole, keyword,  null, "0");
    }

    @Override
    public List<UserAddress> getList(String openid, Integer type) {
        return this.getList(openid, type, null);
    }

    @Override
    public UserAddress get(Long id) {
        return userAddressMapper.selectByPrimaryKey(id);
    }

    @Override
    public UserAddress add(UserAddress userAddress) {
//        List<UserAddress> list = getList(userAddress.getUserId(), null);
//        if (!CollectionUtils.isEmpty(list)){
//            for (UserAddress address : list) {
//                if (address.getMobile() != null && address.getMobile().equals(userAddress.getMobile())){
//                    address.setLastUpdateTime(new Date());
//                    address.setStatus("1");
//                    address.setUpdateTime(new Date());
//                    if (address.getIsDefault() != null && address.getIsDefault() == 1){
//                        userAddress.setIsDefault(1);
//                    }
//                    address.setDelFlag("1");
//                    userAddressMapper.updateByPrimaryKey(address);
//                }
//            }
//        } else {
//            userAddress.setIsDefault(1);
//        }
        String mobile = userAddress.getMobile();
        List<UserAddress> sameMobileList = this.getList(mobile);
        if (!CollectionUtils.isEmpty(sameMobileList)) {
            for (UserAddress address : sameMobileList) {
                userAddressMapper.deleteByPrimaryKey(address.getId());
            }
            boolean present = sameMobileList.stream().anyMatch(address -> StringUtils.isNotBlank(address.getRealId()) && StringUtils.isNotBlank(address.getRealName()));
            if (present) {
                UserAddress realNameAddress = sameMobileList.stream().filter(address -> StringUtils.isNotBlank(address.getRealId()) && StringUtils.isNotBlank(address.getRealName())).findAny().get();
                userAddress.setRealId(realNameAddress.getRealId());
                userAddress.setRealName(realNameAddress.getRealName());
            }
        }
        if (userAddress.getIsDefault() == null){
            userAddress.setIsDefault(0);
        }
        userAddress.setStatus("0");
        userAddress.setDelFlag("0");
        userAddress.setCreateTime(new Date());
        userAddress.setLastUpdateTime(new Date());
        userAddressMapper.insert(userAddress);
        return userAddress;
    }

    @Override
    public int update(UserAddress userAddress) {
        userAddress.setUpdateTime(new Date());
        userAddress.setLastUpdateTime(new Date());
        return userAddressMapper.updateByPrimaryKeySelective(userAddress);
    }

    @Override
    public UserAddress getDefaultAddress(String userId, Integer type) {
        return userAddressMapper.selectUserDefaultAddress(userId, type);
    }

    @Override
    public void setDefault(Long id, int addressType) {
        UserAddress address = this.get(id);
        List<UserAddress> list = this.getList(address.getUserId(), addressType);
        for (UserAddress userAddress : list) {
            if (!userAddress.getId().equals(id)){
                userAddress.setIsDefault(0);
                this.update(userAddress);
            }
        }
        address.setType(addressType);
        address.setIsDefault(1);
        this.update(address);
    }

    @Override
    public boolean check(String openid, Integer type, UserAddress userAddress) {
        List<UserAddress> list = getList(openid, type);
        if (CollectionUtils.isEmpty(list)){
            return false;
        }
        String checkKey = userAddress.getCompany() + userAddress.getProvince() + userAddress.getCity() + userAddress.getArea() + userAddress.getAddress();
        Set<String> collect = list.stream().map(e -> e.getCompany() + e.getProvince() + e.getCity() + e.getArea() + e.getAddress()).distinct().collect(Collectors.toSet());
        return collect.contains(checkKey);
    }

    @Override
    public Object remove(Long id) {
        UserAddress userAddress = this.get(id);
        if (userAddress == null){
            throw new CustomException("此信息不存在");
        }
        userAddress.setDelFlag("1");
        userAddress.setStatus("1");
        userAddress.setUpdateTime(new Date());
        userAddress.setLastUpdateTime(new Date());
        return userAddressMapper.updateByPrimaryKey(userAddress);
    }

    @Override
    public UserAddress get(UserAddress userAddress) {
        List<UserAddress> list = getList(userAddress.getAddress(), userAddress.getType());
        if (CollectionUtils.isEmpty(list)){
            return null;
        }
        String addressKey = userAddress.getMobile();
        Map<String, UserAddress> map = list.stream().collect(Collectors.toMap(e -> e.getMobile(), Function.identity(), (key1, key2) -> key2));
        return map.get(addressKey);
    }

    @Override
    public List<UserAddress> getList(String mobile) {
        return userAddressMapper.selectListByMobile(mobile);
    }

    @Override
    public UserAddress get(String name, String mobile) {
        return userAddressMapper.selectByMobile(name.trim(), mobile.trim());
    }
}
